<template>
    <div class="top-search">
        <div class="search">
            <div class="city-name" @click="onCheckCity">
                {{ addressCity.name }}<i class="iconfont icon-zhankai"></i>  <span>|</span>
            </div>
            <Search ref="searchRef" v-model="checkCityValue" show-action placeholder="请输入地址" @click-input="getSearch" @clear="onClear">
                <template #left-icon>
                    <i class="iconfont icon-sousuo"></i>
                </template>
                <template #action>
                    <label @click="onDownload">批量上传</label>
                </template>
            </Search>
        </div>
        <DropdownMenu active-color="#E60044" :overlay="true" :close-on-click-outside="true" class="class-dropdown">
            <DropdownItem ref="areaRef" title="区域" :title-class="activeId.length?'active':''" @opened="onOpenDropdown">
                <TreeSelect
                    v-model:active-id="activeId"
                    v-model:main-active-index="activeIndex"
                    :items="items"
                    selected-icon="checked"
                    class="areaTree"
                    @click-item="TreeSelectChild"
                />
                <div class="btn-group">
                    <span @click="onResetArea">重置</span><span class="on" @click="onConfirmArea">确定</span>
                </div>
            </DropdownItem>
            <DropdownItem ref="mediaRef" title="媒体" :title-class="(form.mediaTypes&&form.mediaTypes.length)?'active':''" @opened="onOpenDropdown">
                <div class="select-content">
                    <template v-for="(item, index) in tagMediaTypeList" :key="index">
                        <tags-list ref="tagRef" :title="item.title" :is-multiple="true" :data="item.children" label="desc" value="value" :selection-data="form[item.code]" @click="handleClick($event,item.code)" />
                    </template>
                </div>
                <div class="btn-group">
                    <span @click="onResetMedia">重置</span><span class="on" @click="onConfirmMedia">确定</span>
                </div>
            </DropdownItem>
            <DropdownItem ref="projectRef" title="楼宇" :title-class="selectBulidList.length?'active':''" @opened="onOpenDropdown">
                <div class="select-content">
                    <template v-for="(item, index) in tagBulidList" :key="index">
                        <tags-list ref="tagRef" :title="item.title" :is-multiple="true" :show-limit="true" :data="item.children" label="desc" value="value" :selection-data="form[item.code]" @click="handleClick($event,item.code)" />
                    </template>
                </div>
                <div class="btn-group">
                    <span @click="onResetBulid">重置</span><span class="on" @click="onConfirmBulid">确定</span>
                </div>
            </DropdownItem>
        </DropdownMenu>
        <Popup :show="showSearchAction" position="bottom" :style="{ height: '100%' }" close-icon="clear">
            <div class="content">
                  <SearchAddress :currentCity="addressCity" @onConfirm="onAddressConfirm" @changCity="onChangCity" @onCel="showSearchAction=false" :show="showSearchAction" ></SearchAddress>
            </div>
        </Popup>
        <CitySelect :show-action="showAction" @confirm="onSelectConfirm" @close="showAction=false"></CitySelect>
        <Upload :show-popup="isShowUpload" @close="isShowUpload=false" @confirm="confirmFile" ></Upload>
    </div>
</template>

<script lang="ts" setup>
import { defineEmits, reactive, ref, onMounted, defineExpose,computed, watch} from 'vue';
import CitySelect from '@/components/CitySelecter/index.vue';
import Upload from './Upload.vue';
import { Search,DropdownMenu, DropdownItem,TreeSelect,Empty,Popup,Toast ,Icon,NavBar} from 'vant';
import {ParamsModel,CityAddressModel,FileCityModel,SaveDataModel,LocalSearchModel, cityModel,AreaModel} from './topSelecter.module.d';
import {TreeChildModel} from './../CitySelecter/citySelecter.module';
import {buildItemModel,buildSetTitleModel} from '@/views/products/selectByTag/selectByTag.module';
import { allBulidTags} from '@/api/selectByTag';
import { getAreaData} from '@/api/lbs';
import tagsList from '@/components/tagsList.vue';
import SearchAddress from '@/components/SearchAddress/index.vue';

import { useRouter } from 'vue-router';

const router = useRouter();
import { store } from '@/store';
import { Console } from 'console';

interface Ref {
    toggle(): void;
    blur(): void;
    reset():void;
    onFocus():void
}

const emits = defineEmits(['onConfirm','onReset','onOpenDropdown']);
const showAction = ref(false);
const currentCity = reactive<TreeChildModel>({});
const activeIndex = ref(0);
const activeId = ref<string[]>([]);
const items = ref<TreeChildModel[]>([]);
const areaRef = ref<Ref>();
const mediaRef = ref<Ref>();
const projectRef = ref<Ref>();
const showSearchAction = ref(false);
const checkCityValue = ref('');
const searchRef = ref<Ref>();
const tagRef = ref<Ref>();
const isShowUpload = ref(false);
const params = reactive<ParamsModel>({
    projectId: 0,
    cityCode: '',
    areaCodes: [],
    addresses: [],
    mediaTypes: [],
    premisesTypes: [],
    premisesPrices: [],
    premisesAges: [],
    inHouseRates: [],
    parkingNums: [],
    propertyFees: []
});
const setSaveData =reactive<SaveDataModel>({
    city: {},
    areaList: [],
    tagBulidArr: {},
    addresses: [],
});
const tagBulidArr = ref<buildSetTitleModel[]>([
    {code: 'premisesType',title: '物业类型',children: []},
    {code: 'premisesPrice',title: '楼盘价格',children: []},
    {code: 'premisesAge',title: '楼龄',children: []},
    {code: 'inHouseRate',title: '入住率',children: []},
    {code: 'parkingNum',title: '车位数',children: []},
    {code: 'propertyFee',title: '物业费',children: []},
]);
const tagMediaTypesArr = ref<buildSetTitleModel[]>([
    {code: 'mediaTypes',title: '媒体类型',children: []},
]);
interface Form{
    [key: string]: buildItemModel[]
}
const form = reactive<Form>({
});
const currentAddressArr = ref<CityAddressModel[]>([]);
const tagBulid = reactive<Form>({});
const tagBulidList = ref<buildSetTitleModel[]>([]);
const tagMediaTypeList = ref<buildSetTitleModel[]>([]);
const addressCity = reactive<TreeChildModel>({})
const selectBulidList= computed(() => {
    const list =[] as unknown as buildItemModel[];
    Object.keys(form).forEach((key:string)=>{
        if(key!=='mediaTypes'){
            list.push(...form[key]);
        }
    });
    return list;
});
const addresses = computed(() => store.state.app.selectByLbs.addresses);
const getAreaList = async(id:string)=>{
    const areaData = await getAreaData(id);
    const child = areaData.map((item:TreeChildModel)=>{
        return{...item,text: item.name,id: item.id};
    });
    const itemsList = [{text: '区域',children: child}];
    items.value = itemsList as unknown as TreeChildModel[];
};
const getCurrentCity = async()=>{
     // eslint-disable-next-line;
    const city = store.state.app.home?.selectCity
    Object.assign(currentCity,city)
    Object.assign(addressCity,city)
    const id = currentCity.id;
    params.cityCode = id;
    await getAreaList(id);
};
onMounted(async()=>{
    const tagBulidData = await allBulidTags();
    Object.assign(tagBulid,tagBulidData);
    tagBulidList.value = tagBulidArr.value.map((item:buildSetTitleModel)=>{
        const children = tagBulid[item.code] as unknown as buildItemModel[];
        return{code: item.code,title: item.title,children};
    });
    tagMediaTypeList.value = tagMediaTypesArr.value.map((item:buildSetTitleModel)=>{
        let children = tagBulid[item.code] as unknown as buildItemModel[];
        children = children.filter(item => item.value !== 3);
        return{code: item.code,title: item.title,children};
    });
    await getCurrentCity();

});
const handleClick =(val:buildItemModel[],code: string) => {
    if(code){
        form[code] = val;
    }
};
const onConfirmData=()=>{
    const areaList = items.value[0].children;
    setSaveData.areaList = params.areaCodes.map((code:string)=>{
        const area = areaList?.find((item:TreeChildModel)=>item.id===code);
        return {name: area?.text,id: area?.id};
    }) as unknown as AreaModel[];
    setSaveData.tagBulidArr = form;
    setSaveData.city = currentCity as unknown as cityModel;
    setSaveData.addresses = addresses.value
    params.addresses = addresses.value.map((item:FileCityModel)=>{
        return {longitude: item.lng,latitude: item.lat,radius: 3000};
    });
    store.commit('app/setSelectByLbs',setSaveData);
    emits('onConfirm',params);
};
const onResetArea=()=>{
    activeId.value =[];
    params.areaCodes =[];
    setSaveData.areaList=[];
    onConfirmData();
    const areaRefElement = areaRef.value as Ref;
    areaRefElement.toggle();
};
const onClear = ()=>{
    params.addresses =[];
    onConfirmData();
};
const onResetMedia = ()=>{
    params.mediaTypes =[];
    form.mediaTypes = [];
    onConfirmData();
    const mediaRefElement = mediaRef.value as Ref;
    mediaRefElement.toggle();
};
const onResetBulid = ()=>{
    Object.keys(form).forEach((key:string)=>{
        if(key!=='mediaTypes'){
            form[key] = [];
            params[`${key}s`] =[];
        }
    });
    onConfirmData();
    const projectRefElement = projectRef.value as Ref;
    projectRefElement.toggle();
};
const onConfirmArea = ()=>{
    params.areaCodes= activeId.value;
    onConfirmData();
    const areaRefElement = areaRef.value as Ref;
    areaRefElement.toggle();
};
const onConfirmMedia = ()=>{
    params.mediaTypes = form.mediaTypes&&form.mediaTypes.map((item:buildItemModel)=>item.value);
    onConfirmData();
    const mediaRefElement = mediaRef.value as Ref;
    mediaRefElement.toggle();
};
const onConfirmBulid = ()=>{
    Object.keys(form).forEach((key:string)=>{
        if(key!=='mediaTypes'){
            params[`${key}s`]= form[key].map((item:buildItemModel)=>item.value);
        }
    });
    onConfirmData();
    const projectRefElement = projectRef.value as Ref;
    projectRefElement.toggle();

};
const onCheckCity = ()=>{
    showAction.value = true;
};
const onSelectConfirm = async (val:TreeChildModel)=>{
    params.areaCodes =[];
    params.cityCode = val.id
    activeId.value=[];
    Object.assign(addressCity,val)
    await getAreaList(val.id);
    showAction.value = false;
    showSearchAction.value = true;

};
const onChangCity = async (val:TreeChildModel)=>{
    params.areaCodes =[];
    params.cityCode = val.id
    activeId.value=[];
    Object.assign(addressCity,val)
    await getAreaList(val.id);
};

const TreeSelectChild = (val:TreeChildModel)=>{
    const index = params.areaCodes.findIndex((id:string)=>id===val.id);
    if(index>-1){
        params.areaCodes.splice(index,1);
    }else{
        params.areaCodes.push(val.id);
    }

};
const goBack = ()=>{
    router.back();
};
const onDownload = ()=>{
    isShowUpload.value = true;
};
const getSearch = ()=>{
    const searchRefElement = searchRef.value as Ref;
    searchRefElement.blur();
    showSearchAction.value = true;
};


const confirmFile = (val:FileCityModel[])=>{
    const FileAddress = val.filter((item:FileCityModel)=>item.success&&item.cityName===currentCity.name);

    if(FileAddress.length){
        setSaveData.addresses = FileAddress.map(item=>{
            return {...item,radius: 3000,title: item.address}
        });
        params.addresses = FileAddress.map((item:FileCityModel)=>{
            return {longitude: item.lng,latitude: item.lat,radius: 3000};
        });
        params.areaCodes =[];
        activeId.value=[];
        store.commit('app/setSelectByLbs',setSaveData);
        onConfirmData();
    }else{
        Toast.fail('上传表格数据必须为当前选中城市的有效地址')
    }

    isShowUpload.value =false;

};

const getAddress = ()=>{
    if(currentAddressArr.value.length){
        // 这里先写到 store 中再读出来，有问题
        setSaveData.addresses = currentAddressArr.value.map((item:CityAddressModel)=>{
            let lat = item.lat||item.point.lat;
            let lng = item.lng||item.point.lng;
            let cityName = item.cityName||item.city;
            return {address: item.address,lat: lat,lng: lng,cityName: cityName,title: item.title,radius: 3000};
        });
        params.addresses = currentAddressArr.value.map((item:CityAddressModel)=>{
            let lat = item.lat||item.point.lat;
            let lng = item.lng||item.point.lng;
            return {longitude: lng,latitude: lat,radius: 3000};
        });
        Object.assign(currentCity,addressCity)
        showSearchAction.value = false;
        store.commit('app/setSelectByLbs',setSaveData);
        onConfirmData();
    }else{
         Toast.fail('请选择搜索地址')
    }

};
const onAddressConfirm = (addressArr:CityAddressModel[])=>{
    currentAddressArr.value = addressArr;
    getAddress()

}
const onOpenDropdown = ()=>{
    emits('onOpenDropdown')
}
// const onCloseAddress = ()=>{
//     if(params.addresses.length){
//         showSearchAction.value = false;
//     }else{
//        Toast.fail('请选择搜索地址')
//     }
// }
// watch(() => addresses.value,(val)=>{
//     if (!params.addresses.length) {
//         params.addresses = addresses.value.map(item => {
//             return { longitude: item.lng, latitude: item.lat, radius: 3000, title: item.title, address: item.address, cityName: item.cityName };
//         });
//     }
// });

defineExpose({
    getSearch,
});
</script>

<style lang="scss" scoped>
.top-search {
    width: 345px;
    margin: auto;
    :deep(.van-dropdown-item) {
        position: fixed;
        left: 15px;
        right: 15px;
    }
}
.search {
    width: 100%;
    height: 48px;
    background: #fff;
    border-radius: 6px 6px 0 0;
    border-bottom: 0.5px solid #f0f0f0;
    overflow: hidden;
    .city-name {
        font-size: 14px;
        color: #333333;
        min-width: 45px;
        float: left;
        line-height: 50px;
        padding-left: 12px;
    }
    span {
        color: #dadada;
        padding-left: 5px;
    }
    label {
        font-size: 14px;
        color: #397ff8;
        padding-right: 5px;
    }
    ::v-deep {
        [class~="van-search__content"] {
            background: #fff;
        }
        [class~="van-search"] {
            padding-left: 0;
        }
    }
    .back-icon {
        color: #333;
        padding-right: 3px;
        margin-top: 5px;
    }
}
.class-dropdown {
    ::v-deep {
        [class~="van-overlay"] {
            background: none;
        }
        [class~="van-dropdown-menu__bar"] {
            box-shadow: none;
            height: 44px;
        }
    }
}
.select-content {
    padding: 12px 12px 0;
    overflow: auto;
    max-height: 300px;
    .select-item {
        // margin-bottom:20px;
        .item-title {
            font-weight: bold;
            font-size: 14px;
            color: #333333;
            padding: 0 12px;
            margin-bottom: 12px;
        }
        .list {
            display: flex;
            flex-wrap: wrap;
            // padding-left: 12px;
            span {
                display: inline-block;
                width: 98px;
                height: 32px;
                background: #f8f8f8;
                border-radius: 6px;
                text-align: center;
                line-height: 32px;
                margin-left: 12px;
                border: 0.5px solid #f8f8f8;
                margin-bottom: 20px;
                font-size: 13px;
                &.on {
                    background: #e600440f;
                    border: 0.5px solid #e6004466;
                    color: #e60044;
                }
            }
        }
    }
}
::v-deep {
    [class~="van-sidebar-item--select::before"] {
        background-color: #e60044;
        font-weight: normal;
        font-size: 13px;
    }
    [class~="van-sidebar-item--select:active"] {
        color: #e60044;
        font-weight: normal;
        font-size: 13px;
    }
    [class~="van-tree-select__item--active"] {
        color: #e60044;
        font-weight: normal;
        font-size: 13px;
    }
    [class~="van-sidebar-item--select"] {
        color: #e60044;
        font-weight: normal;
        font-size: 13px;
    }
    [class~="van-tree-select__item"] {
        font-weight: normal;
        font-size: 13px;
    }
    [class~="active"] {
        color: #e60044;
        font-weight: normal;
        font-size: 13px;
    }
    [class~="van-dropdown-menu__title"] {
        font-size: 13px;
        font-weight: normal;
    }
    .van-button {
        background-color: #e60044;
        border: 0;
        border-radius: 6px;
    }
}
.btn-group {
    padding: 12px;
    box-sizing: border-box;
    background: #fff;
    display: flex;
    justify-content: space-between;
    span {
        display: inline-block;
        width: 110px;
        height: 38px;
        background: #eeeeee;
        border-radius: 6px;
        line-height: 38px;
        font-size: 14px;
        color: #333333;
        text-align: center;
        &.on {
            display: inline-block;
            width: 202px;
            height: 38px;
            background: #e60044;
            border-radius: 6px;
            line-height: 38px;
            font-size: 14px;
            color: #ffffff;
            text-align: center;
        }
    }
}
.icon-zhankai {
    display: inline-block;
    font-size: 12px;
    transform: scale(0.6, 0.6);
    color: #ddd;
    padding-left: 5px;
}
.content {
    display: flex;
    flex-direction: column;
    height: 100%;
    min-height: 100%;
    .city-list {
        padding: 12px;
        overflow: auto;
        li {
            padding: 16px 0;
            display: flex;
            justify-content: space-between;
        }
        span {
            &.on {
                color: #f7135e;
            }
        }
    }
    ::v-deep {
        [class~="van-search__content"] {
            background: #f8f8f8;
            border-radius: 6px;
        }
    }
}
.search-content {
    padding: 0 12px;
    margin-top: 6px;
    .search-title {
        display: flex;
        justify-content: space-between;
        span {
            font-weight: bold;
            font-size: 14px;
            color: #333333;
        }
    }
    .select-city {
        margin-top: 15px;
        span {
            display: inline-block;
            padding: 3px 12px;
            background: #fafafa;
            border-radius: 4px;
            margin-bottom: 10px;
        }
    }
}

</style>
